package com.shadow.demo.excel.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shadow.demo.common.bo.R;
import com.shadow.demo.common.constants.NumericConstant;
import com.shadow.demo.data.excel.entity.EasyExcelEntity;
import com.shadow.demo.data.excel.mapper.EasyExcelMapper;
import com.shadow.demo.excel.poi.MSExcelHelper;
import com.shadow.demo.excel.demo.v2.vo.EasyExcelExportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class EasyExcelService extends ServiceImpl<EasyExcelMapper, EasyExcelEntity> {

    @Resource
    public EasyExcelMapper easyExcelMapper;

    public List<EasyExcelExportVO> getExportList(Map<String, Object> params) {
        QueryWrapper<EasyExcelEntity> wrapper = new QueryWrapper<>();

        List<EasyExcelEntity> easyExcelEntityList = easyExcelMapper.selectList(wrapper);
        List<EasyExcelExportVO> easyExcelExportVOList = new ArrayList<>();
        easyExcelEntityList.forEach(x -> {
             EasyExcelExportVO easyExcelExportVO = new EasyExcelExportVO();
             BeanUtils.copyProperties(x, easyExcelExportVO);
             easyExcelExportVOList.add(easyExcelExportVO);
        });
        return easyExcelExportVOList;
    }

    public R batchImport(final InputStream fis) throws IOException {
        final List<EasyExcelExportVO> resultList = new ArrayList<>();
        final List<List<String>> contents = MSExcelHelper.readXlsText(fis, 0, -1);
        int index = 0;
        for (List<String> l : contents) {
            if (index > 1) {
                EasyExcelExportVO userRoleRel = new EasyExcelExportVO();
                userRoleRel.setName(l.get(NumericConstant.NUMBER_ONE));
                userRoleRel.setAge(Integer.parseInt(l.get(NumericConstant.NUMBER_TWO)));
                userRoleRel.setPersonality(l.get(NumericConstant.NUMBER_THREE));
                userRoleRel.setAssets(new BigDecimal(l.get(NumericConstant.NUMBER_FOUR)));
                resultList.add(userRoleRel);
            }
            index++;
        }
        //取出数据库中已经存在的
        final StringBuilder msgBuilder = new StringBuilder();
        List<EasyExcelEntity> userRoleRelList = list();
        if (CollectionUtils.isNotEmpty(userRoleRelList)) {
            // 获取数据校验结果
            getMsgBuilder(msgBuilder, resultList, userRoleRelList);
            if (StringUtils.isEmpty(msgBuilder.toString())) {
                for (EasyExcelExportVO r:resultList) {
                    r.setCreateTime(LocalDateTime.now());
                    r.setModifyTime(LocalDateTime.now());
                    EasyExcelEntity easyExcelEntity = new EasyExcelEntity();
                    BeanUtils.copyProperties(r, easyExcelEntity);
                    save(easyExcelEntity);
                }
                // 同时记录日志
                msgBuilder.append("导入成功！");
            } else {
                msgBuilder.append("请修改后重新导入数据！");
            }
        } else {
            msgBuilder.append("无数据导入！");
        }
        return R.success(R.MSG, msgBuilder.toString());
    }

    public EasyExcelEntity getByName(final String name) {
        LambdaQueryWrapper<EasyExcelEntity> wrapper = new QueryWrapper<EasyExcelEntity>()
                .lambda()
                .eq(EasyExcelEntity::getName, name);
        return easyExcelMapper.selectOne(wrapper);
    }

    /**
     * 获取数据校验消息.
     * @param msgBuilder 校验消息存储对象
     * @param resultList 结果列表
     * @param userRoleRelList 用户角色列表
     **/
    public void getMsgBuilder(
            final StringBuilder msgBuilder,
            final List<EasyExcelExportVO> resultList,
            final List<EasyExcelEntity> userRoleRelList
    ) {
        for (int i = 0; i < resultList.size(); i++) {
            msgBuilder.append("第");
            msgBuilder.append(i + NumericConstant.NUMBER_THREE);
            msgBuilder.append("行:");
            final String msgTitle = msgBuilder.toString();
            Optional.ofNullable(resultList.get(i).getName()).ifPresent(str -> msgBuilder.append("OA账号不能为空<br/>"));
            for (int j = 0; j < userRoleRelList.size(); j++) {
                if (resultList.get(i).getName().equals(userRoleRelList.get(j).getName())) {
                    msgBuilder.append("行数据已经存在用户角色资源库内，请不要重复导入！<br/>");
                }
            }
            Optional.ofNullable(msgTitle).filter(StringUtils::isNotBlank)
                    .filter(msg -> msg.equals(msgBuilder.toString()))
                    .ifPresent(msg -> msgBuilder.delete(0, msgBuilder.length()));
        }
    }
}
